package top.infopub.security.filter;


import java.io.Serializable;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import top.infopub.security.util.SessionUserUtils;


/**
 * 并发登录控制器
 * @author Awoke
 * @version 2018年9月17日
 * @see ConcurrentLoginControlFilter
 * @since
 */
public class ConcurrentLoginControlFilter extends AccessControlFilter {
    
    /**
     * log
     */
    private final static Logger log = LoggerFactory.getLogger(ConcurrentLoginControlFilter.class);

    /**
     * 踢出后地址
     */
    private String kickoutUrl;

    /**
     * 默认踢出之前登录的用户
     */
    private boolean kickoutAfter = false;

    /**
     * 同一个帐号最大会话数 默认1
     */
    private int maxSession = 1;

    /**
     * username pre key
     */
    private static String KEY_PRE_USERNAME = "info-concurrent-";

    private SessionManager sessionManager;

    private Cache<String, Deque<Serializable>> cache;

    private AbstractSessionDAO sessionDAO;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response,
                                      Object mappedValue)
        throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
        throws Exception {
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            // 如果没有登录，直接进行之后的流程
            return true;
        }
        Session session = subject.getSession();
        String username = SessionUserUtils.getSessionUserName();
        Serializable sessionId = session.getId();
        Deque<Serializable> deque = cache.get(getCacheKey(username));
        if (deque == null) {
            // deque = new LinkedList<Serializable>();
            deque = new ConcurrentLinkedDeque<Serializable>();
        }
        boolean isChangeCache = false;
        // 如果队列里没有此sessionId，且用户没有被踢出，放入队列
        if (!deque.contains(sessionId)) {
            deque.addLast(sessionId);
            isChangeCache = true;
            // this.cache.put(getCacheKey(username), deque);
        }
        // 如果队列里的sessionId数超出最大会话数，开始踢人
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            if (!kickoutAfter) { // 如果踢出前者
                kickoutSessionId = deque.removeFirst();
                isChangeCache = true;
            }
            else { // 否则踢出后者
                kickoutSessionId = deque.removeLast();
                isChangeCache = true;
            }
            try {
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(
                    kickoutSessionId));
                if (kickoutSession != null) {
                    sessionDAO.delete(kickoutSession);
                }
            }
            catch (Exception e) {
                log.info(e.getMessage());
            }
        }
        if (isChangeCache) {
            this.cache.put(getCacheKey(username), deque);
        }
        // 如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute("kickout") != null) {
            try {
                subject.logout();
            }
            catch (Exception e) {
                log.info(e.getMessage());
            }
            saveRequest(request);
            WebUtils.issueRedirect(request, response, kickoutUrl);
            return false;
        }
        return true;
    }

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("concurrent-login:");
    }

    private String getCacheKey(String userName) {
        return KEY_PRE_USERNAME + userName;
    }

    public AbstractSessionDAO getSessionDAO() {
        return sessionDAO;
    }

    public void setSessionDAO(AbstractSessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }
}
